package com.ukadas.eduko.controlador.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.faces.bean.ManagedProperty;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.ukadas.eduko.negocio.GestorImagenes;

@WebServlet("/SVFoto")
public class SVFoto extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	@ManagedProperty(value="#{gestorImagenes}")
	private GestorImagenes gestorImagenes;
	
	public SVFoto() {
		super();
	}
	
	public void init(){
    	WebApplicationContext appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
    	gestorImagenes = (GestorImagenes) appCtx.getBean("gestorImagenes");
    }
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		/*response.setContentType("text/plain");
		response.setCharacterEncoding("iso-8859-1");*/

		response.setContentType("image/jpg");
		PrintWriter out = response.getWriter();
	
		int id = Integer.parseInt(request.getParameter("id"));
		String nombreClase = request.getParameter("clase");
		String campoId = request.getParameter("campoId");
		
		System.out.println("He recibido "+id+" " +nombreClase+" "+campoId);
		try {
			//gestorImagenes.getImagen(id, Class.forName(nombreClase), campoId);
			response.getOutputStream().write(gestorImagenes.getImagen(id, Class.forName(nombreClase), campoId),0,gestorImagenes.getImagen(id, Class.forName(nombreClase), campoId).length);
			System.out.println(gestorImagenes.getImagen(id, Class.forName(nombreClase), campoId));
			response.getOutputStream().flush();
		} catch (ClassNotFoundException e) {
			System.out.println("SE HA PRODUCIDO UN ERROR."+e.getMessage());
			e.printStackTrace();
		}
		
		try {
			out.print(gestorImagenes.getImagen(id, Class.forName(nombreClase), campoId));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		//out.print("hola caracola");
		out.flush();

	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	}

	public GestorImagenes getGestorImagenes() {
		return gestorImagenes;
	}

	public void setGestorImagenes(GestorImagenes gestorImagenes) {
		this.gestorImagenes = gestorImagenes;
	}
}




